<template>
    <div class="white-box">
        <title-more title="交易设置" />
        <cell-tip tip="修改交易设置后，记得点击下方确认保存按钮，否则数据不同步更新。" />

        <el-form ref="ruleRef" :model="ruleForm" :rules="ruleCheck" label-width="240px">
            <el-form-item label="平台是否关闭交易" prop="trans_switch" required>
                <el-switch
                    v-model="ruleForm.trans_switch"
                    width="72px"
                    size="large"
                    :inactive-value="0"
                    :active-value="1"
                    inline-prompt
                    active-text="已开启"
                    inactive-text="已关闭"
                />
            </el-form-item>
            <el-form-item label="交易关闭提示语" prop="close_text" v-if="!ruleForm.trans_switch">
                <el-input v-model.trim="ruleForm.close_text" type="textarea" clearable :rows="4" placeholder="请输入交易关闭提示语" />
                <div class="input-tips">平台关闭后展示的提示语</div>
            </el-form-item>
            <el-form-item label="供应商商品审核" prop="good_switch" required>
                <el-switch
                    v-model="ruleForm.good_switch"
                    width="72px"
                    size="large"
                    :inactive-value="0"
                    :active-value="1"
                    inline-prompt
                    active-text="已开启"
                    inactive-text="已关闭"
                />
            </el-form-item>
            <!-- <el-form-item label="验证手机号" prop="check_mobile" required>
                <el-switch
                    v-model="ruleForm.check_mobile"
                    width="72px"
                    size="large"
                    :inactive-value="0"
                    :active-value="1"
                    inline-prompt
                    active-text="已开启"
                    inactive-text="已关闭"
                />
                <div class="input-tips">关闭则会隐藏获取<code>手机验证码</code>功能</div>
            </el-form-item> -->
            <el-form-item label="完善头像及昵称" prop="user_audit" required>
                <el-switch
                    v-model="ruleForm.user_audit"
                    width="72px"
                    size="large"
                    :inactive-value="0"
                    :active-value="1"
                    inline-prompt
                    active-text="已开启"
                    inactive-text="已关闭"
                />
                <div class="input-tips">开启时，下单必须完善头像及昵称（已完善的用户不会出现提示）</div>
            </el-form-item>
            <el-form-item label="会员注册验证" prop="user_verify" required>
                <el-switch
                    v-model="ruleForm.user_verify"
                    width="72px"
                    size="large"
                    :inactive-value="0"
                    :active-value="1"
                    inline-prompt
                    active-text="已开启"
                    inactive-text="已关闭"
                />
                <div class="input-tips">开启时，下单会员必须注册（已注册的用户不会出现提示）</div>
            </el-form-item>
            <el-form-item label="是否生成货架号" prop="shelves_switch" required v-if="versions && versions.version_id > 2">
                <el-switch
                    v-model="ruleForm.shelves_switch"
                    width="72px"
                    size="large"
                    :inactive-value="0"
                    :active-value="1"
                    inline-prompt
                    active-text="已开启"
                    inactive-text="已关闭"
                />
            </el-form-item>
            <el-form-item label="预计生成货架号" prop="create_shelve_day" v-show="ruleForm.shelves_switch == 0 && versions && versions.version_id > 2">
                <el-date-picker v-model="ruleForm.create_shelve_day" type="date" value-format="YYYY-MM-DD" placeholder="请选择生成货架号日期" />
            </el-form-item>
            <el-form-item label="平台交易" prop="trans_time">
                <el-time-picker
                    v-model="ruleForm.trans_time"
                    is-range
                    format="HH:mm"
                    range-separator="~"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    @change="changeDates"
                />
                <div class="input-tips">平台交易的开始时间与结束时间，单位：分</div>
            </el-form-item>
            <!-- <el-form-item label="秒杀时间" prop="skill_time">
                <el-time-picker
                    v-model="ruleForm.skill_time"
                    is-range
                    format="HH:mm"
                    range-separator="~"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    @change="changeSkillDates"
                />
                <div class="input-tips">秒杀活动的开始时间与结束时间，单位：分。秒杀结束时间不能大于平台交易结束时间</div>
            </el-form-item> -->
            <el-form-item label="停止交易时间" prop="stop_time">
                <el-input v-model.trim="ruleForm.stop_time" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入停止交易分钟数" />
                <span class="form-item__char">分</span>
                <div class="input-tips">平台交易结束<code>X分钟</code>不能下单</div>
            </el-form-item>
            <el-form-item label="销售倍数" prop="sales_fold">
                <el-input v-model.trim="ruleForm.sales_fold" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入销售倍数" />
                <div class="input-tips"><code>本场交易量</code>=<code>销售倍数</code>x<code>本场交易量</code>，最低为1</div>
            </el-form-item>
            <el-form-item label="取消订单" prop="auto_cancel">
                <el-input
                    v-model.trim="ruleForm.auto_cancel"
                    oninput="value=value.replace(/[^\d]/g,'')"
                    clearable
                    placeholder="请输入取消订单分钟数, 限3~15分钟"
                />
                <span class="form-item__char">分</span>
                <div class="input-tips">待付款订单等待<code>X分钟</code>后用户不付款则自动取消订单</div>
            </el-form-item>
            <el-form-item label="自动确认收货" prop="confirm_time">
                <el-input v-model.trim="ruleForm.confirm_time" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入自动确认收货天数" />
                <span class="form-item__char">天</span>
                <div class="input-tips">平台发货超过<code>X天</code>"未确认收货"，自动确认收货</div>
            </el-form-item>
            <el-form-item label="申请售后时间" prop="refund_time">
                <el-input v-model.trim="ruleForm.refund_time" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入申请售后天数" />
                <span class="form-item__char">天</span>
                <div class="input-tips">订单确认完成/确认收货后<code>X天</code>可以申请售后</div>
            </el-form-item>
            <el-form-item label="最低购买数量提醒" prop="buy_limit">
                <el-input v-model.trim="ruleForm.buy_limit" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入最低购买数量提醒" />
                <span class="form-item__char">扎</span>
                <div class="input-tips">当购买数量少于<code>X扎</code>，用户端结算页会提醒</div>
            </el-form-item>
            <el-form-item>
                <div class="foot-btn flexs-center">
                    <el-button type="primary" :loading="form_loading" @click="submitForm(ruleRef)"> 确认保存 </el-button>
                    <el-button @click="resetForm(ruleRef)">重置</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive, computed } from "vue"
import { useBaseStore } from "@store/base"
import GoBack from "@components/GoBack.vue"
import TitleMore from "@components/title-more.vue"
import CellTip from "@components/cell-tip.vue"

const { proxy } = getCurrentInstance()

const storeBase = useBaseStore()
const versions = computed(() => {
    return storeBase.versions
})

onMounted(() => {
    getInfo()
})

function getInfo() {
    proxy.$axios
        .get("config/deal")
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                // 将时分格式化
                let now = new Date()
                let startArr = result.trade_start_time.split(":")
                let trans_start_time = new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(startArr[0]), Number(startArr[1]))
                let endArr = result.trade_end_time.split(":")
                let trans_end_time = new Date(now.getFullYear(), now.getMonth(), now.getDate(), endArr[0], endArr[1])

                ruleForm.trans_switch = Number(result.sys_stop || 0)
                ruleForm.close_text = result.sys_stop_info
                ruleForm.sales_fold = result.sales_fold || 1 // 交易倍数
                ruleForm.create_shelve_day = result.create_shelve_day
                // ruleForm.check_mobile = Number(result.check_mobile)
                ruleForm.user_audit = Number(result.user_audit || 0)
                ruleForm.user_verify = Number(result.user_verify || 0)
                ruleForm.shelves_switch = Number(result.create_shelve || 0)
                ruleForm.good_switch = Number(result.product_verify || 0)
                ruleForm.trans_start_time = result.trade_start_time
                ruleForm.trans_end_time = result.trade_end_time
                ruleForm.auto_cancel = result.auto_cancel
                ruleForm.trans_time = [trans_start_time, trans_end_time]
                ruleForm.stop_time = result.stop_trade
                ruleForm.confirm_time = result.auto_finish
                ruleForm.refund_time = result.refund_days
                ruleForm.buy_limit = result.buy_limit
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 保存
 * @param {Boolean} form_loading 弹窗按钮状态
 * @property {Array} ruleRef 表单规则
 * @property {Object} ruleForm  表单字段
 * @property {Object} ruleCheck  表单提示
 */
const form_loading = ref(false)
const ruleRef = ref(null)
const ruleForm = reactive({
    trans_switch: 1,
    good_switch: 1,
    shelves_switch: 1,
    trans_time: [],
    trans_start_time: "", // 平台交易开始时间
    trans_end_time: "", // 平台交易结束时间
    // skill_time: [],
    skill_start_time: "", // 秒杀开始时间
    skill_end_time: "", // 秒杀结束时间
    stop_time: "",
    refund_time: "",
    confirm_time: "",
    create_shelve_day: "", // 预计生成货架号时间
    auto_cancel: 3, // 取消订单
    close_text: "",
    buy_limit: "",
    sales_fold: 1,
    user_verify: 1, // 会员注册
    // check_mobile: 0, // 验证手机号
    user_audit: 0, // 头像及昵称
})
const ruleCheck = reactive({
    trans_time: [{ type: "array", required: true, message: "请选择平台交易开始至结束时间", trigger: "change" }],
    // skill_time: [{ type: "array", required: true, validator: compareTime, trigger: "change" }],
    stop_time: [{ required: true, message: "请输入停止交易分钟数", trigger: "blur" }],
    auto_cancel: [{ required: true, validator: cancelTime, trigger: "blur" }],
    refund_time: [{ required: true, message: "请输入申请售后天数", trigger: "blur" }],
    buy_limit: [{ required: true, message: "请输入最低购买数量提醒", trigger: "blur" }],
    confirm_time: [{ required: true, message: "请输入自动确认收货天数", trigger: "blur" }],
    sales_fold: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
})
// 取消订单分钟时
function cancelTime(rule, value, callback) {
    if (value == '') {
        callback(new Error("请输入取消订单分钟数, 限3~15分钟"))
    } else if (ruleForm.auto_cancel < 3 || ruleForm.auto_cancel > 15) {
        callback(new Error("取消订单分钟仅限3~15分钟！"))
    } else {
        callback()
    }
}
// 自定义时分比较大小
function compareTime(rule, value, callback) {
    if (value.length == 0) {
        callback(new Error("请选择秒杀开始和结束时间"))
    } else if (timeTostamp(ruleForm.trans_start_time) - timeTostamp(ruleForm.skill_start_time) > 0) {
        callback(new Error("秒杀开始时间不能小于平台交易开始时间！"))
    } else if (timeTostamp(ruleForm.trans_end_time) - timeTostamp(ruleForm.skill_end_time) < 0) {
        callback(new Error("秒杀结束时间不能大于平台交易结束时间！"))
    } else {
        callback()
    }
}
// 确认
const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            if (!ruleForm.trans_switch && ruleForm.close_text == "") {
                proxy.$message({ message: "请输入交易关闭提示语", type: "warning" })
                return
            }
            if (!ruleForm.sales_fold || ruleForm.sales_fold < 1) {
                proxy.$message({ message: "销售倍数最低为1", type: "warning" })
                return
            }
            form_loading.value = true
            let data = {
                sys_stop: ruleForm.trans_switch,
                sys_stop_info: ruleForm.close_text,
                create_shelve: ruleForm.shelves_switch,
                product_verify: ruleForm.good_switch,
                trade_start_time: ruleForm.trans_start_time,
                trade_end_time: ruleForm.trans_end_time,
                stop_trade: ruleForm.stop_time,
                auto_finish: ruleForm.confirm_time,
                refund_days: ruleForm.refund_time,
                auto_cancel: ruleForm.auto_cancel,
                buy_limit: ruleForm.buy_limit,
                sales_fold: ruleForm.sales_fold,
                // check_mobile: ruleForm.check_mobile,
                user_audit: ruleForm.user_audit,
                user_verify: ruleForm.user_verify,
            }
            if (ruleForm.shelves_switch == 0) {
                data.create_shelve_day = ruleForm.create_shelve_day
            }
            proxy.$axios
                .post("config/deal", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        proxy.$message({ message: "保存成功", type: "success" })
                        getInfo()
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

// 平台交易时间
const changeDates = (val) => {
    if (val) {
        let time1 = proxy.$util.formatAtTimes(val[0])
        let time2 = proxy.$util.formatAtTimes(val[1])
        ruleForm.trans_start_time = time1.substring(0, time1.length - 3)
        ruleForm.trans_end_time = time2.substring(0, time2.length - 3)
    }
}

// 秒杀时间-结束时间不能大于平台交易结束时间
const changeSkillDates = (val) => {
    if (val) {
        let time1 = proxy.$util.formatAtTimes(val[0])
        let time2 = proxy.$util.formatAtTimes(val[1])
        ruleForm.skill_start_time = time1.substring(0, time1.length - 3)
        ruleForm.skill_end_time = time2.substring(0, time2.length - 3)
    }
}
//将时分秒转为时间戳
function timeTostamp(time) {
    if (time !== null) {
        let s = ""
        let hour = time.split(":")[0]
        let min = time.split(":")[1]
        console.log("hour", hour)
        console.log("min", min)
        // let sec = time.split(":")[2] // 只比较时分，排除秒
        // s = Number(hour * 3600) + Number(min * 60) + Number(sec)
        s = hour * 3600 + min * 60
        console.log("s", s)
        return s
    }
}
</script>
<script>
export default {
    name: "TransactionSetup",
}
</script>

<style lang="less" scoped>
.form-item__char {
    color: @gray-7;
    font-size: @font-size-md;
    margin-left: @margin-sm;
}
</style>
